package com.uliky.shouyiLibrary.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.uliky.common.constant.AuthServerConstant;
import com.uliky.common.exception.BizCodeEnume;
import com.uliky.common.utils.R;
import com.uliky.common.utils.RandomUtil;
import com.uliky.common.vo.MemberRespVo;
import com.uliky.shouyiLibrary.auth.feign.MemberFeignService;
import com.uliky.shouyiLibrary.auth.feign.ThirdPartFeignSService;
import com.uliky.shouyiLibrary.auth.vo.UserLoginVo;
import com.uliky.shouyiLibrary.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {
    @Autowired
    ThirdPartFeignSService thirdPartFeignSService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignService memberFeignService;
    @GetMapping("/sms/sendCode")
    @ResponseBody
    public R serdCode(@RequestParam("phone") String phone) {

        //TODO：接口防刷
        //2。验证码的校验  -- 存redis
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String redisCache = redisTemplate.opsForValue().get(key);
        if (redisCache != null) {
            //redis有，说明已经发过
            //验证码
            //String redisCode = redisCache.split("_")[0];
            //发送时间
            Long serdTime = Long.valueOf(redisCache.split("_")[1]);
            if (System.currentTimeMillis() - serdTime < 60000) {
                //60秒内又接收到发送验证码请求，返回错误
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(), BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        String code = RandomUtil.getSixBitRandom();
        //加上系统时间，判断60秒内是否重复发送
        String Rediscode = code + "_" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, Rediscode, 5, TimeUnit.MINUTES);
        thirdPartFeignSService.sendCode(phone, code);
        return R.ok();
    }
    @PostMapping("/register")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult result, RedirectAttributes redirectAttributes){
        //格式校验
        if(result.hasErrors()) {
            //将错误信息返回到注册页面
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,FieldError::getDefaultMessage));
//            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.shouyiLibrary.com/reg.html";
        }
        //真正注册 -- 远程调用
        //验证验证码：
        String code = userRegistVo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        if(!StringUtils.isEmpty(s)) {
            //校验
            String redisCode = s.split("_")[0];
            if (code.equals(redisCode)) {
                //删除验证码 令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
                //验证码校验成功
                //真正注册 -- 远程调用
                R regist = memberFeignService.regist(userRegistVo);
                if(regist.getCode() == 0) {
                    //注册成功回到首页
                    return "redirect:http://auth.shouyiLibrary.com/login.html";
                }else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg",regist.getData("msg",new TypeReference<String>(){}));
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.shouyiLibrary.com/reg.html";
                }


            }else {
                //验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code","验证码错误");
                redirectAttributes.addFlashAttribute("errors",errors);
                //校验出错，转发到注册页
                return "redirect:http://auth.shouyiLibrary.com/reg.html";
            }
        }else {
            //过期
            Map<String, String> errors = new HashMap<>();
            errors.put("code","验证码已过期");
            redirectAttributes.addFlashAttribute("errors",errors);
            //校验出错，转发到注册页
            return "redirect:http://auth.shouyiLibrary.com/reg.html";
        }
    }
    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes,
                        HttpSession session) {
        //远程校验
        R login = memberFeignService.login(vo);
        if(login.getCode() == 0) {
            //登录成功，跳转到首页
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {});
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://shouyiLibrary.com";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:http://auth.shouyiLibrary.com/login.html";
        }
    }
    /**
     * 登录页判断
     */
    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        if(session.getAttribute(AuthServerConstant.LOGIN_USER) == null) {
            return "login";
        }else {
            return "redirect:http://shouyiLibrary.com";
        }
    }
}